<?php


namespace App\Http\Controllers\Mini;


use App\Http\Controllers\Controller;
use App\Models\Label;
use Illuminate\Http\Request;

class LabelController extends Controller
{
    private $user_id;

    public function __construct()
    {
        $id = auth('user')->id();

        $this->user_id = $id;
    }

    //获取标签列表
    public function list()
    {
        $data = Label::query()->select('id', 'title')->where('status', 1)->get();

        return $this->success($data);
    }


    /**
     * 上传图片接口
     * @param Request $request
     */
    public function uploadImg(Request $request)
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            return $this->error('请先登录');
        }

        if ($request->hasFile('file')) {
            //获取图片
            $file = $request->file('file');
            //验证图片合法性
            $res = $this->checkFile($file, ['png', 'jpg', 'jpeg']);
            if ($res === true) {
                $path = $file->store('images/mini/circle');
                if ($path) {
                    return $this->success(['path' => $path], '上传成功');
                }

            }
            return $this->error($res);
        }

        return $this->error('没有上传图片');
    }

    /**
     * 验证文件合法性
     * @param \Illuminate\Http\UploadedFile $file
     * @param array $extension
     * @param int $size 2m
     * @return bool|string
     */
    private function checkFile($file, $extension, $size = 2048000)
    {
        $fileExtension = strtolower($file->extension());
        if (!in_array($fileExtension, $extension)) {
            return '文件类型不允许';
        }

        $fileSize = $file->getSize();
        if ($fileSize >= $size) {
            return '图片大于2M';
        }

        return true;
    }
}
